﻿using System;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dziennik_ProfilNauczyciela {
    public static class SQLInterface {
        public static SqlConnection conn;
        public static SqlDataReader reader;
        public static DziennikDataContext linqDataContext;
        public static int userId;
        public static int rodzaj;
        

        static SQLInterface() {
            conn = null;
            reader = null;
            userId = 0;
            rodzaj = 0;
        }

        public static int Login(string login, string haslo) {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.ConnectTimeout = 5;
            builder.DataSource = "192.168.56.101,6003";
            builder.InitialCatalog = "dziennik";
            builder.IntegratedSecurity = false;
            builder.Password = haslo;
            builder.UserID = "dziennik_" + login;
            conn = new SqlConnection(builder.ConnectionString);
            try {
                conn.Open();
            }
            catch (Exception e) {
                if (conn.State == ConnectionState.Closed)
                    return 1;//zle haslo
            }
            if (conn.State == ConnectionState.Closed) return 2;//blad polaczenia
            else {
                userId = Int32.Parse(login);
                SqlCommand cmd = new SqlCommand("select dziennik.dbo.getUserType()", conn);
                reader = cmd.ExecuteReader();
                reader.Read();
                rodzaj = (int)reader[0];
                reader.Close();
                if (!(rodzaj == 1 || rodzaj == 2)) {
                    Logout();
                    return 3;
                }
                else {
                    linqDataContext = new DziennikDataContext(conn);
                    return 0;
                }
            }
        }
        public static void Logout() {
            linqDataContext = null;
            reader.Close();
            conn.Close();
            userId = 0;
            rodzaj = 0;
        }
        public static string PobierzDaneOsobowe() {
            SqlCommand cmd = new SqlCommand("select tytulNaukowy, imie, nazwisko from dziennik.dbo.nauczyciele where userId = " + userId, conn);
            reader = cmd.ExecuteReader();
            reader.Read();
            string ret = (string)reader[0] + " " + (string)reader[1] + " " + (string)reader[2] + " - " + userId;
            reader.Close();
            return ret;
        }
    }
}
